// pages/reconciliation/reconciliation.js
import {
    billByStoreId,
    billDetailStoreId,
    billDetailStoreIdExcel,
    storeUserInfo
} from '../../api/api';
import {
    toast
} from '../../utils/wxApi';
import {
    numToString,
    timeFormat
} from '../../utils/util';

Page({

    data: {
        showCalendar: false,
        type: 1, //0全部  1贊欠
        date: [],
        storeInfo: {},
        totalBill: {},
        statistics: {},
        list: [],
        userList: [],
        maxDate: '',
        minDate: '',
        startTime: '',
        endTime: '',
        today: '',
        tabsOffsetTop: 30,
        isTabsFixed: false,
        canvasWidth: 375,
        canvasHeight: 300,
        isGeneratingImage: false,
        shareImageUrl: '',
        authFailed: false
    },


    onLoad(options) {
        // 检查是否已登录
        const token = wx.getStorageSync('token');
        if (!token) {
            // 保存当前页面信息，登录后重定向
            const route = 'pages/reconciliation/reconciliation';
            const params = Object.keys(options).map(key => `${key}=${options[key]}`).join('&');
            const redirectUrl = params ? `/${route}?${params}` : `/${route}`;
            wx.setStorageSync('redirectUrl', redirectUrl);
            
            // 跳转到首页登录
            wx.reLaunch({
                url: '/pages/index/index'
            });
            return;
        }
        
        this.page = 1;
        this.limit = 10;
        const {
            storeId,
            storeName,
            username,
            maijia_id
        } = options
        if (storeName || username) {
            this.setData({
                storeInfo: {
                    storeName: decodeURIComponent(storeName || ''),
                    username: decodeURIComponent(username || '')
                }
            })
        }
        this.storeId = storeId;
        // 保存买家ID，用于后续过滤
        this.maijia_id = maijia_id;
        // 标记已经加载过，用于 onShow 判断
        this._hasLoaded = false;
        
        this.getStoreUserInfo().then(() => {
            // 如果有 maijia_id，自动选中对应的买家（支持逗号分隔的多个ID）
            if (this.maijia_id && this.data.userList.length > 0) {
                const idSet = new Set(String(this.maijia_id).split(',').filter(Boolean));
                this.data.userList.forEach((user, index) => {
                    const selected = idSet.has(String(user.id));
                    this.setData({
                        [`userList[${index}].disabled`]: !selected
                    })
                })
            }
            this.getBillByStoreId()
            this.getBillDetailStoreId()
            // 标记已经完成首次加载
            this._hasLoaded = true;
        })

        const windowInfo = wx.getWindowInfo()
        this.setData({
            maxDate: timeFormat(new Date(), 'yyyy-mm-dd'),
            minDate: timeFormat(new Date(2020, 0, 1), 'yyyy-mm-dd'),
            tabsOffsetTop: 86 * windowInfo.screenWidth / 750
        })
    },
    handleNoAuth() {
        this.setData({ authFailed: true });
        wx.showModal({
            title: '提示',
            content: '身份认证失败，无权查看',
            showCancel: false,
            confirmText: '确定',
            success: (modalRes) => {
                if (modalRes.confirm) {
                    wx.reLaunch({
                        url: `/pages/index/index`,
                    });
                }
            }
        });
    },
    onShow() {
        // 页面显示时刷新数据，确保从分享进入时也能加载数据
        if (this.storeId && this._hasLoaded) {
            console.log('onShow - 刷新数据');
            this.page = 1;
            this.total = 0;
            this.getStoreUserInfo().then(() => {
                // 如果有 maijia_id，自动选中对应的买家（支持逗号分隔的多个ID）
                if (this.maijia_id && this.data.userList.length > 0) {
                    const idSet = new Set(String(this.maijia_id).split(',').filter(Boolean));
                    this.data.userList.forEach((user, index) => {
                        const selected = idSet.has(String(user.id));
                        this.setData({
                            [`userList[${index}].disabled`]: !selected
                        })
                    })
                }
                this.getBillByStoreId()
                this.getBillDetailStoreId()
            })
        }
    },

    onPullDownRefresh() {
        this.page = 1;
        this.total = 0;
        this.getStoreUserInfo().then(() => {
            this.getBillByStoreId()
            this.getBillDetailStoreId()
        })

        wx.stopPullDownRefresh()
    },

    onReachBottom() {
        this.page += 1;
        this.getBillDetailStoreId()
    },
    selectedUser(e) {
        console.log(e.currentTarget.dataset.i)
        const i = e.currentTarget.dataset.i;
        if (!this.data.userList[i]?.id) return
        this.setData({
            [`userList[${i}].disabled`]: !this.data.userList[i].disabled
        })
        this.page = 1;
        this.total = 0;
        this.getBillByStoreId()
        this.getBillDetailStoreId()
    },
    selectTime() {
        this.setData({
            showCalendar: true,
            endTime: this.data.endTime || timeFormat(new Date(), 'yyyy-mm-dd')
        })
    },
    onClose() {
        this.setData({
            showCalendar: false
        })
    },
    bindDateChange1(e) {
        console.log('开始时间', e.detail.value)
        this.setData({
            startTime: e.detail.value
        })
    },
    bindDateChange2(e) {
        console.log('结束时间', e.detail.value)
        this.setData({
            endTime: e.detail.value
        })
    },
    formatDate(date) {
        date = new Date(date);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onConfirm(event) {
        if (!this.data.startTime) return toast('请选择开始时间');
        if (!this.data.endTime) return toast('请选择结束时间');
        if (new Date(this.data.endTime).getTime() < new Date(this.data.startTime).getTime()) return toast('开始时间应小于结束时间');
        this.setData({
            showCalendar: false,
            date: [this.data.startTime, this.data.endTime],
        });
        this.page = 1;
        this.total = 0;
        this.getBillDetailStoreId()
    },
    clearDate() {
        this.setData({
            showCalendar: false,
            date: [],
            startTime: '',
            endTime: ''
        });
        this.page = 1;
        this.total = 0;
        this.getBillDetailStoreId()
    },
    onTabsScroll(e) {
        // van-sticky scroll 事件：e.detail.isFixed 用于判断吸顶状态
        const isFixed = !!(e && e.detail && e.detail.isFixed);
        if (isFixed !== this.data.isTabsFixed) {
            this.setData({ isTabsFixed: isFixed });
        }
    },
    switchTabs(e) {
        const type = e.currentTarget.dataset.type
        this.setData({
            type: +type,
        })
        this.page = 1;
        this.total = 0;
        this.getBillDetailStoreId()
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
        })
    },
    toDetail(e) {
        const i = e?.currentTarget?.dataset?.i;
        if (!this.rawData || !this.rawData[i]) return toast('缺少订单详情数据')
        const targetOrder = this.rawData[i];
        if (!targetOrder?.id) return toast('订单缺少ID')
        wx.navigateTo({
            url: `/pages/orderDetail/orderDetail?orderId=${targetOrder.id}&storeName=${encodeURIComponent(this.data.storeInfo?.storeName || '')}&username=${encodeURIComponent(this.data.storeInfo?.username || '')}&totalPaying=${this.data.totalBill?.paying || 0}`,
        })
    },
    toTransactionRecord() {
        // 获取选中的用户ID列表
        let selectedUserIds = [];
        this.data.userList.forEach(it => {
            if (!it.disabled && it.id) {
                selectedUserIds.push(it.id);
            }
        });
        
        // 将用户ID用逗号拼接
        const maijiaIds = selectedUserIds.join(',');
        
        wx.navigateTo({
            url: `/pages/transactionRecord/transactionRecord?maijia_id=${maijiaIds}&store_id=${this.storeId}`,
        })
    },
    async getBillDetailStoreId() {
        console.log(this.total, this.data.list.length)
        if (this.total && this.data.list.length >= this.total) return
        const params = {
            store_id: this.storeId,
            type: this.data.type,
            page: this.page,
            limit: this.limit
        };
        if (this.data.date.length) {
            params.start_time = this.data.date[0];
            params.end_time = this.data.date[1];
        }
        let uid = [];
        this.data.userList.forEach(it => {
            if (!it.disabled) uid.push(it.id)
        })
        if (uid.length) {
            params.user_id = uid.join();
        }
        try {
            const res = await billDetailStoreId(params, {
                showLoading: true
            })
            if (res?.code === 403) {
                this.handleNoAuth();
                return;
            }
            if (!res?.data) return
            const dataList = res?.data?.data?.data || [];
            this.rawData = this.page == 1 ? dataList : this.rawData.concat(dataList);

            const list = dataList.map(item => {
                const sheqian_price = numToString((item.total_price || 0) + (item.duoshou || 0) - (item.youhui || 0) - (item.huan || 0));
                const order_detail = item?.order_detail?.map(it => {
                    return {
                        goods_name: it.goods_name,
                        goods_id: it.goods_id,
                        status: it.status,
                        price: it.price,
                        num: it.num,
                        other_num: it.other_num,
                        weight: it.weight,
                        unit: it.unit,
                        total_price: it.total_price,
                        fujiafei: it.fujiafei,
                        huozhu_num: it.huozhu_num, // 有值时，"包出门" 文字就会显示
                    }
                })
                return {
                    add_time: item.add_time.substring(0, 10),
                    total_price: item.total_price,
                    id: item.id,
                    huan: item.huan,
                    maijia: item.maijia,
                    duoshou: item.duoshou,
                    youhui: item.youhui,
                    status: item.status,
                    sheqian_price,
                    order_detail
                }
            })
            const totalList = this.page == 1 ? list : this.data.list.concat(list)
            this.total = res?.data?.data?.total || 0;
            this.setData({
                list: totalList,
                statistics: res?.data?.statistics || {},
                today: timeFormat(new Date(), 'yyyy-mm-dd'),
            })
        } catch (error) {

        }
    },
	
	
	async exportExcel() {
	  
	    const params = {
	        store_id: this.storeId,
	        type: this.data.type,
	        page: this.page,
	        limit: this.limit
	    };
	    if (this.data.date.length) {
	        params.start_time = this.data.date[0];
	        params.end_time = this.data.date[1];
	    }
	    let uid = [];
	    this.data.userList.forEach(it => {
	        if (!it.disabled) uid.push(it.id)
	    })
	    if (uid.length) {
	        params.user_id = uid.join();
	    }
	    try {
	        const res = await billDetailStoreIdExcel(params, {
	            showLoading: true
	        })
	        
	         wx.downloadFile({
	         		url: res.data.url,
	         		success: function(res) {
	         		console.log(res)
	         		 wx.openDocument({
	         		         filePath: res.tempFilePath,
	         		         showMenu:true, //默认是false，为true的时候，右上角有三个点
	         		         success: function (res) {
	         		           console.log('打开文档成功')
	         		         }
	         		       })
	         		},
	         		
	         	  });
	        
	    } catch (error) {
	
	    }
	},
	
	
	
	 
	

 
	
    async getBillByStoreId() {
        const params = {
            store_id: this.storeId
        };
        let uid = [];
        this.data.userList.forEach(it => {
            if (!it.disabled) uid.push(it.id)
        })
        if (uid.length) {
            params.user_id = uid.join();
        }
        const res = await billByStoreId(params, {
            showLoading: true
        })
        if (!res?.data) return
        this.setData({
            totalBill: res.data
        })
    },
    async getStoreUserInfo() {
        return new Promise(async (resolve, reject) => {
            const res = await storeUserInfo({
                store_id: this.storeId
            }, {
                showLoading: true
            })
            if (!res?.data) return reject(res)
            this.setData({
                userList: res?.data?.user || []
            })
            resolve(res?.data?.user || [])
        })

    },

    // 创建分享图片
    createShareImage() {
        return new Promise((resolve, reject) => {
            const ctx = wx.createCanvasContext('shareCanvas');
            const {canvasWidth, canvasHeight, totalBill, storeInfo} = this.data;

            // 设置背景色
            ctx.setFillStyle('#f5fafe');
            ctx.fillRect(0, 0, canvasWidth, canvasHeight);

            // 添加边框
            ctx.setStrokeStyle('#f0f0f0');
            ctx.setLineWidth(1);
            ctx.strokeRect(0, 0, canvasWidth, canvasHeight);

            // 绘制买家名称（标题）- 加粗效果
            ctx.setFillStyle('#000000');
            ctx.setFontSize(36);
            ctx.setTextAlign('left');
            const buyerName = storeInfo.storeName || '商家';
            // 多次绘制模拟加粗
            ctx.fillText(buyerName, 29, 60);
            ctx.fillText(buyerName, 29.5, 60);
            ctx.fillText(buyerName, 29, 60.5);
            ctx.fillText(buyerName, 29.5, 60.5);

            // 绘制副标题 "贊欠金额" - 字体较大
            ctx.setFillStyle('#999999');
            ctx.setFontSize(24);
            ctx.fillText('赊欠金额', 30, 100);

            // 绘制订单数 "(X单)" - 字体较小，并留有间距
            const labelWidth = ctx.measureText('赊欠金额').width;
            ctx.setFontSize(20);
            const orderNum = totalBill.paying_num || 0;
            ctx.fillText(`(${orderNum}单)`, 30 + labelWidth + 8, 100);

            // 绘制金额（大号绿色）- 加粗效果
            ctx.setFillStyle('#3abe2c');
            ctx.setFontSize(48);
            ctx.setTextAlign('left');
            const amount = totalBill.paying || 0;
            const amountText = `¥${numToString(amount)}`;
            // 多次绘制模拟加粗
            ctx.fillText(amountText, 30, 160);
            ctx.fillText(amountText, 30.5, 160);
            ctx.fillText(amountText, 30, 160.5);
            ctx.fillText(amountText, 30.5, 160.5);

            // 计算日期范围
            const endDate = new Date();
            const startDate = new Date();
            const days = totalBill.paying_day || 0;
            startDate.setDate(endDate.getDate() - days);
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            const dateRange = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;

            // 绘制日期范围
            ctx.setFillStyle('#666666');
            ctx.setFontSize(18);
            ctx.fillText(dateRange, 30, 200);

            // 绘制底部绿色渐变按钮区域（带圆角）
            const btnX = 30;
            const btnY = canvasHeight - 70;
            const btnWidth = canvasWidth - 60;
            const btnHeight = 50;
            const btnRadius = 2;

            // 绘制圆角矩形
            ctx.beginPath();
            ctx.moveTo(btnX + btnRadius, btnY);
            ctx.lineTo(btnX + btnWidth - btnRadius, btnY);
            ctx.arcTo(btnX + btnWidth, btnY, btnX + btnWidth, btnY + btnRadius, btnRadius);
            ctx.lineTo(btnX + btnWidth, btnY + btnHeight - btnRadius);
            ctx.arcTo(btnX + btnWidth, btnY + btnHeight, btnX + btnWidth - btnRadius, btnY + btnHeight, btnRadius);
            ctx.lineTo(btnX + btnRadius, btnY + btnHeight);
            ctx.arcTo(btnX, btnY + btnHeight, btnX, btnY + btnHeight - btnRadius, btnRadius);
            ctx.lineTo(btnX, btnY + btnRadius);
            ctx.arcTo(btnX, btnY, btnX + btnRadius, btnY, btnRadius);
            ctx.closePath();

            // 填充渐变色（135度,从青绿到草绿）
            const gradient = ctx.createLinearGradient(btnX, btnY, btnX + btnWidth, btnY + btnHeight);
            gradient.addColorStop(0.2, '#009481'); // 青绿色（20%）
            gradient.addColorStop(1, '#52b316'); // 草绿色（100%）
            ctx.setFillStyle(gradient);
            ctx.fill();

            // 绘制按钮文字
            ctx.setFillStyle('#ffffff');
            ctx.setFontSize(20);
            ctx.setTextAlign('center');
            ctx.fillText('查看订单详情', canvasWidth / 2, btnY + btnHeight / 2 + 6);

            // 绘制完成后，生成图片
            ctx.draw(false, () => {
                setTimeout(() => {
                    wx.canvasToTempFilePath({
                        canvasId: 'shareCanvas',
                        success: (res) => {
                            console.log('分享图片生成成功:', res.tempFilePath);
                            this.setData({
                                shareImageUrl: res.tempFilePath,
                                isGeneratingImage: false
                            });
                            resolve(res.tempFilePath);
                        },
                        fail: (err) => {
                            console.error('生成图片失败:', err);
                            this.setData({
                                isGeneratingImage: false
                            });
                            reject(err);
                        }
                    });
                }, 300);
            });
        });
    },

    // 分享配置
    onShareAppMessage(options) {
        console.log('分享被点击', options);
        
        // 显示 loading
        wx.showLoading({
            title: '正在生成分享图片...',
            mask: true
        });

        // 标记正在生成
        this.setData({
            isGeneratingImage: true
        });

        // 返回 Promise，异步生成图片
        return this.createShareImage().then(imagePath => {
            wx.hideLoading();

            // 读取当前选中的买家ID（未禁用的即选中）
            const selectedUserIds = [];
            (this.data.userList || []).forEach(it => {
                if (!it.disabled && it.id) selectedUserIds.push(it.id);
            });
            const maijiaParam = selectedUserIds.length ? `&maijia_id=${encodeURIComponent(selectedUserIds.join(','))}` : '';

            // 构建分享路径，带上 storeId、storeName、username 以及当前买家过滤（支持多选）
            const sharePath = `/pages/reconciliation/reconciliation?storeId=${this.storeId}&storeName=${encodeURIComponent(this.data.storeInfo.storeName || '')}&username=${encodeURIComponent(this.data.storeInfo.username || '')}${maijiaParam}`;

            return {
                title: `${this.data.storeInfo.storeName || '商家'}`,
                path: sharePath,
                imageUrl: imagePath
            };
        }).catch(error => {
            wx.hideLoading();
            wx.showToast({
                title: '生成图片失败',
                icon: 'none'
            });
            // 返回默认分享内容
            return {
                title: '欠款提醒',
                path: '/pages/reconciliation/reconciliation'
            };
        });
    }

})
